import createId from "@/lib/createId";

const localStorageKeyName = 'tagList';

const tagStore= {
    //tag store
    tagList: [] as Tag[],

    fetchTags(){
        this.tagList = JSON.parse(window.localStorage.getItem(localStorageKeyName) || '[]');
        return this.tagList
    },
    // tagList : tagListModel.fetch(),
    findTag(id: string){
        return this.tagList.filter(t => t.id === id)[0]
    },
    createTag (name: string) {
        //this.data=[{id:'1',name:'1'},{id:'2',name:'2'}]
        const names = this.tagList.map(item => item.name)
        if (names.indexOf(name) >= 0) {
            // return false
            // throw new Error('重复了')
            alert('您即将要新增的标签已经存在了，不能新增成功')
            return '重复了';
        }
        const id = createId().toString()
        this.tagList.push({id: id, name: name});
        this.saveTags();
        alert('创建成功')
        return 'success';
    },
    removeTag (id: string){
        let index = -1
        for (let i = 0; i < this.tagList.length; i++) {
            if (this.tagList[i].id === id)
                index = i;
            break;
        }
        this.tagList.splice(index, 1)
        this.saveTags()
        return true
    },
    updateTag(id: string, name: string) {
        const idList = this.tagList.map(item => item.id)
        if (idList.indexOf(id) >= 0) {
            const names = this.tagList.map(item => item.name)
            if (names.indexOf(name) >= 0) {
                return '重复了'
            } else {
                const tag = this.tagList.filter(item => item.id === id)[0]
                tag.name = name
                // this.save// 写的这行 帮我整惨了
                this.saveTags()
                return 'success'
            }
        } else {
            return 'not found'
        }
    },
    saveTags() {
        window.localStorage.setItem(localStorageKeyName, JSON.stringify(this.tagList));
    }
};

tagStore.fetchTags();  // 一般叫做init函数

export default tagStore;
